package com.itbaizhan.shopping_seckill_service.redis;

/**
 * @author spf
 * @date 2024/1/24
 * @time 22:03
 */

import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.pojo.SeckillGoods;
import com.itbaizhan.shopping_common.service.SecKillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis过期具体做什么
 */
@Component
public class RedisKeyExpairationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SecKillService secKillService;

    public RedisKeyExpairationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 订单过期后，关闭交易，回退库存
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取id
        String id = message.toString();
        // 从redi副本中获取value
        Orders orders = (Orders) redisTemplate.opsForValue().get(id + "_copy");
        Long goodId = orders.getCartGoods().get(0).getGoodId();
        Integer num = orders.getCartGoods().get(0).getNum();
        // 查询秒杀商品
        SeckillGoods seckillGoods = secKillService.findSecKillGoodsByRedis(goodId);
        seckillGoods.setStockCount(seckillGoods.getStockCount() + num);
        redisTemplate.boundHashOps("seckillGoods").put(goodId, seckillGoods);

        // 删除订单数据
        redisTemplate.delete(id + "_copy");
    }
}
